import axios from "axios";

export const instance = axios.create({
    baseURL: 'http://127.0.0.1:8000/auth',
    timeout: 1000
})

// 请求拦截器，在请求头中添加token认证信息
instance.interceptors.request.use(
    config => {
        // 登录用户才需要access token
        const accessToken = localStorage.getItem('access')
        accessToken && (config.headers.Authorization = `Bearer ${accessToken}`)
        config.headers['Content-Type'] = 'Application/json'
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

export const anonymousInstance = axios.create({
    baseURL: 'http://127.0.0.1:8000/auth',
    timeout: 1000
})

// 请求拦截器，未登录用户不需要携带token信息
anonymousInstance.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'Application/json'
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

/*
// 使用refresh口令去获取access口令(token)
const fetchAccessToken = async () => {
    const response = await instance.post('jwt/refresh/',
        {'refresh': localStorage.getItem('refresh')})
    if (response && response.data) {
        return response.data.access
    }
    return null
}

// 响应拦截器
instance.interceptors.response.use(
    response => {
        return response
    },
    async function(error) {
        const originalRequest = error.config
        if (error.response.status === 401 && !originalRequest._restry) {
            originalRequest._restry = true
            const access_token = await fetchAccessToken()
            if (access_token)
                axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token
        }
        return Promise.reject(error)
    }
)
 */